const { Controller } = require("egg");

class downloadController extends Controller {
  async list() {
    const download = await this.service.download.list();
    this.ctx.helper.success(download);
  }

  async create() {
    const { ctx, service } = this;
    const { updateAt, title, link } = ctx.request.body;

    if (!updateAt || !title || !link) {
      return this.ctx.helper.error("updateAt、title或link不能为空");
    }

    const result = await service.download.create({
      updateAt,
      title,
      link,
    });
    this.ctx.helper.success(result, "材料创建成功");
  }

  async delete() {
    const { ctx, service } = this;
    const { id } = ctx.request.body;

    if (!id) {
      return this.ctx.helper.error("参数异常：缺少id");
    }
    const result = await service.download.delete(id);
    if (result === null) {
      return this.ctx.helper.error("材料不存在");
    }
    this.ctx.helper.success(result, "材料删除成功");
  }

  async update() {
    const { ctx, service } = this;
    const { updateAt, title, link, id } = ctx.request.body;

    if (!id) {
      return this.ctx.helper.error("参数异常：缺少材料ID");
    }
    const result = await service.download.update(id, { title, link, updateAt });
    if (result[0] === 0) {
      return this.ctx.helper.error("更新失败，材料不存在");
    }
    this.ctx.helper.success(result, "材料更新成功");
  }
}

module.exports = downloadController;
